package com.itheima.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.common.PaginationVO;
import com.itheima.entity.SysMenu;
import com.itheima.entity.SysRole;
import com.itheima.entity.addRole;
import com.itheima.mapper.MenuMapper;
import com.itheima.mapper.RoleMapper;
import com.itheima.service.RoleService;
import com.itheima.vo.MenuVO;
import com.itheima.vo.RoleVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class RoleServiceImpl implements RoleService {
    private final RoleMapper roleMapper;
    private final MenuMapper menuMapper;

    public RoleServiceImpl(RoleMapper roleMapper, MenuMapper menuMapper) {
        this.roleMapper = roleMapper;
        this.menuMapper = menuMapper;
    }

    @Override
    public PaginationVO<RoleVO> page(Integer limit, Integer page, String name) {
        PageHelper.startPage(page, limit);
        List<SysRole> roleList = roleMapper.getAllRole(name);
        List<RoleVO> roleVOList = new ArrayList<>();
        PageInfo<SysRole> pageInfo = new PageInfo<>(roleList);
        long count = pageInfo.getTotal();
        int totalPages = pageInfo.getPages(); // 总页数
        int pageSize = pageInfo.getPageSize(); // 每页显示的数据条数
        int currentPage = pageInfo.getPageNum(); // 当前页码
        List<SysRole> sysRoleList1 = pageInfo.getList();
        sysRoleList1.forEach(sysRole -> roleVOList.add(sysRole.getRoleVO()));
        PaginationVO<RoleVO> paginationVO = new PaginationVO<>();
        paginationVO.setCount(count);
        paginationVO.setTotalPages(totalPages);
        paginationVO.setPageSize(pageSize);
        paginationVO.setCurrentPage(currentPage);
        paginationVO.setData(roleVOList);
        return paginationVO;
    }

    @Override
    public List<RoleVO> allData() {
        List<SysRole> roleList = roleMapper.getAllRole();
        List<RoleVO> roleVOList = new ArrayList<>();
        roleList.forEach((role) -> {
            RoleVO roleVO = new RoleVO();
            roleVO.setId(role.getId());
            roleVO.setName(role.getName());
            roleVO.setDescription(role.getDescription());
            roleVO.setCreate_date(role.getCreateDate());
            roleVO.setUpdate_date(role.getUpdateDate());
            roleVO.setRemarks(role.getRemarks());
            roleVO.setDel_flag(role.getDelFlag());
            roleVO.setSuperadmin(role.getSuperadmin());
            roleVO.setDefault_data(role.getDefaultData());
            roleVOList.add(roleVO);

        });
        return roleVOList;
    }

    @Override
    public void addRole(addRole role) {
        String id = UUID.randomUUID().toString();
        Map<String, String> map = new HashMap<>();
        String[] menuids = role.getMenuids();
        for (String menuid : menuids) {
            map.put(menuid, id);
        }
        System.out.println(map);
        map.forEach((key, value) -> {
            System.out.println(value + ":" + key);
            roleMapper.addMenu(value, key);
        });
        SysRole sysRole = new SysRole();
        sysRole.setId(id);
        sysRole.setName(role.getName());
        sysRole.setDescription(role.getDescription());
        sysRole.setCreateDate(LocalDateTime.now());
        sysRole.setUpdateDate(LocalDateTime.now());
        sysRole.setDelFlag("0");
        sysRole.setSuperadmin("1");
        sysRole.setDefaultData("1");
        roleMapper.addRole(sysRole);
    }

    @Override
    public RoleVO rowInfoRole(String id) {
        // 角色信息
        SysRole sysRole = roleMapper.rowInfoRole(id);
        // 角色菜单列表信息
        List<SysMenu> sysMenuList = menuMapper.selectListByRoleIds(Collections.singletonList(sysRole.getId()));
        // 将角色信息变成树状结构
        List<MenuVO> sysMenus = covertVOTree(sysMenuList);
        RoleVO sysRoleVO = sysRole.getRoleVO();
        sysRoleVO.setAuthList(sysMenus);
        return sysRoleVO;
    }

    @Override
    @Transactional
    public void delRoleById(String id) {
        roleMapper.delRoleMenuById(id);
        roleMapper.delRoleById(id);
    }

    @Override
    public void updateRole(addRole role) {
        RoleVO roleVO = new RoleVO();
        roleVO.setId(role.getId());
        roleVO.setName(role.getName());
        roleVO.setDescription(role.getDescription());
        roleVO.setUpdate_date(LocalDateTime.now());

        Map<String, String> map = new TreeMap<>();
        Arrays.stream(role.getMenuids()).forEach(num -> {
            map.put(num, role.getId());
        });
        roleMapper.delRoleMenuById(role.getId());
        map.forEach((key, value) -> {
            roleMapper.addMenu(value,key);
        });
        roleMapper.updateRole(roleVO);
    }

    private List<MenuVO> covertVOTree(List<SysMenu> sysMenuList) {
        // 获取顶层菜单的逻辑 就是pid为0
        List<MenuVO> topLayerMenus = sysMenuList.stream()
                .filter(sysMenu -> sysMenu.getPid() == 0)
                .map(SysMenu::getMenv)
                .collect(Collectors.toList());
        topLayerMenus.forEach(sysMenuItem1 -> {
            // 获取第一层的子集
            List<MenuVO> menus2 = sysMenuList.stream()
                    .filter(sysMenu -> sysMenu.getPid().equals(sysMenuItem1.getId()))
                    .map(SysMenu::getMenv)
                    .collect(Collectors.toList());

            menus2.forEach(sysMenuItem2 -> {
                // 获取第二层的子集
                List<MenuVO> menus3 = sysMenuList.stream()
                        .filter(sysMenu -> sysMenu.getPid().equals(sysMenuItem2.getId()))
                        .map(SysMenu::getMenv)
                        .collect(Collectors.toList());
                sysMenuItem2.setChildren(menus3);
            });

            sysMenuItem1.setChildren(menus2);
        });
        return topLayerMenus;
    }
}